
package com.gack.helper.common.vidyo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 

  * @ClassName: VidyoWebServiceAPI

  * @Description: vidyo 视频会议相关的webservice接口

  * @author lsy

  * @date 2018年8月27日 下午1:47:05

  *
 */
public class VidyoWebServiceAPI {
	private static final String WEBSERVICE_URL = "http://guoan.byshang.cn/services/v1_1/VidyoPortalAdminService";
	
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: addRoom
	
	  * @Description: 创建会议室
	
	  * @param @param preElement
	  * @param @param elementBody
	  * @param @return    
	
	  * @return boolean 成功OK,失败NO
	
	  * @throws
	 */
	public static boolean addRoom(Map<String, String> elementBody) throws DocumentException {
		// 参数包装成xml
		String parameter = PackageSoapXml.builder().packageAddRoom(VidyoConstant.ADD_ROOM_REQUEST, elementBody);
		// 发送httpsoap 请求
		String resultXml = HttpSoapRequest(WEBSERVICE_URL, VidyoConstant.ADD_ROOM, parameter);
		// 解析请求的返回值
		String result = HttpSoapResponse(resultXml, VidyoConstant.ADD_ROOM_RESPONSE);
		
		return result.equals(VidyoConstant.OK) ? true : false;
	}
	
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: deleteRoom
	
	  * @Description: 删除会议室
	
	  * @param @param elementBody
	  * @param @return    
	
	  * @return boolean 成功OK,失败NO
	
	 */
	public static boolean deleteRoom(Map<String, String> elementBody) throws DocumentException  {
		// 包装xml，封装参数
		String parameter = PackageSoapXml.builder().packageDeleteRoom(VidyoConstant.DELETE_ROOM_REQUEST, elementBody);
		// 发送httpsoap 请求
		String resultXml = HttpSoapRequest(WEBSERVICE_URL, VidyoConstant.DELETE_ROOM, parameter);
		String result = HttpSoapResponse(resultXml, VidyoConstant.DELETE_ROOM_RESPONSE);
		// 解析返回值
		return result.equals(VidyoConstant.OK) ? true : false;
	}
	
	/**
	 * 
	
	  * @Title: getRooms
	
	  * @Description: 查询会议室
	
	  * @param @param elementBody
	  * @param @return    
	
	  * @return 查询会议室后的xml
	
	  * @throws
	 */
	public static String getRooms(Map<String, String> elementBody) {
		// 包装xml，封装参数
		String parameter = PackageSoapXml.builder().packageGetRooms(VidyoConstant.GET_ROOMS_REQUEST, elementBody);
		// 发送请求
		String resultXml = HttpSoapRequest(WEBSERVICE_URL, VidyoConstant.GET_ROOMS, parameter);
		return resultXml;
	}
	
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: getParticipants
	
	  * @Description: 获取会议室参与人详情
	
	  * @param @param elementBody
	  * @param @return    
	
	  * @return String 
	
	  * @throws
	 */
	public static String getParticipants(Map<String, String> elementBody) throws DocumentException {
		String parameter = PackageSoapXml.builder().packageGetParticipants(VidyoConstant.GET_PARTICIPANTS_REQUEST, elementBody);
		String resultXml = HttpSoapRequest(WEBSERVICE_URL, VidyoConstant.GET_PARTICIPANTS, parameter);
		return resultXml;
	}
	
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: leaveConference
	
	  * @Description: 移除会议室参会人员
	
	  * @param @param elementBody
	  * @param @return    
	
	  * @return boolean 成功OK,失败NO
	
	  * @throws
	 */
	public static boolean leaveConference(Map<String, String> elementBody) throws DocumentException {
		String parameter = PackageSoapXml.builder().pakageLeaveConference(VidyoConstant.LEAVE_CONFERENCE_REQUEST, elementBody);
		String resultXml = HttpSoapRequest(WEBSERVICE_URL, VidyoConstant.LEAVE_CONFERENCE, parameter);
		String result = HttpSoapResponse(resultXml, VidyoConstant.LEAVE_CONFERENCE_RESPONSE);
		// 解析返回值
		return result.equals(VidyoConstant.OK) ? true : false;
		
	}
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: inviteToConference
	
	  * @Description: 邀请其余厂商视频系统入会
	
	  * @param @param elementBody
	  * @param @return    
	
	  * @return boolean 成功 OK，失败NO
	
	  * @throws
	 */
	public static boolean inviteToConference(Map<String, String> elementBody) throws DocumentException {
		String parameter = PackageSoapXml.builder().packageInviteToConference(VidyoConstant.INVITE_TO_CONFERENCE_REQUEST, elementBody);
		String resultXml = HttpSoapRequest(WEBSERVICE_URL, VidyoConstant.INVITE_TO_CONFERENCE, parameter);
		String result = HttpSoapResponse(resultXml, VidyoConstant.INVITE_TO_CONFERENCE_RESPONSE);
		// 解析返回值
		return result.equals(VidyoConstant.OK) ? true : false;
	}
	/**
	 * 
	
	  * @Title: HttpSoapRequest
	
	  * @Description: 发送Soap请求，调用vidyo接口
	
	  * @param @param url 地址
	  * @param @param functionName 方法名
	  * @param @param parameter 参数
	  * @param @return    
	
	  * @return String 
	
	  * @throws
	 */
	public static String HttpSoapRequest(String url, String functionName, String parameter) {
		String xmlString = null;
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		post.addHeader("Content-Type", "text/xml; charset=UTF-8"); 
	    post.addHeader("Authorization", "Basic YWRtaW46YWRtaW4wMQ==");
	    post.setHeader("SOAPAction",functionName);
	    StringEntity myEntity = new StringEntity(parameter,"UTF-8");
        post.setEntity(myEntity);
        HttpResponse response = null;
		try {
			response = client.execute(post);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
        try {
        	if (response != null) {
        		xmlString = EntityUtils.toString(response.getEntity());
        	}
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
        return xmlString;
	}
	
	/**
	 * 
	
	  * @Title: HttpSoapResponse
	
	  * @Description: 解析返回的xml，如果返回OK则调用成功，否则失败。
	
	  * @param @param xml 返回的xml内容
	  * @param @param funcionName 方法名称，为了拼接元素使用
	
	  * @return String 
	
	  * @throws
	 */
	public static String HttpSoapResponse(String xml, String funcionName) throws DocumentException{
		Document dom = DocumentHelper.parseText(xml);
		
		if (dom == null)
			return VidyoConstant.NO;
		
		Element root = dom.getRootElement();  
        Element body = root.element("Body");
        Element Response = body.element(funcionName);
        if (Response == null)
        	return VidyoConstant.NO;
        
        Element Ok = Response.element(VidyoConstant.OK);
        return (Ok != null) ? Ok.getText() : VidyoConstant.NO;
		
	}
	
	/**
	 * 
	
	  * @Title: getRoomsResult 暂时废弃
	
	  * @Description: 解析查询会议室返回的数据，把xml解析成Map集合。
	  * total 为查询的总数
	  * listReult 为查询的会议室集合，里面的map存储会议室相关元素
	
	  * @param @param xml 返回的xml
	  * @param @return
	  * @param @throws DocumentException    
	
	  * @return Map<String,Object> 
	
	  * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getRoomsResult(String xml) throws DocumentException{
		// 要返回的map集合
		Map<String, Object> result = new HashMap<>();
		// 存储room的map集合
		Map<String, Object> listMap = null;
		// 存储listMap的list集合
		List<Map<String, Object>> listReult = new ArrayList<>();
		
		Document dom = DocumentHelper.parseText(xml);
		if (dom == null) {
			return null;
		}
		// 获取root 节点
		Element root = dom.getRootElement();
		Element body = root.element("Body");
		Element getRoomsResponse = body.element(VidyoConstant.GET_ROOMS_RESPONSE);
		if (getRoomsResponse == null) {
			return null;
		}
		
		
		Iterator<Element> getRoomsResponseIterator = getRoomsResponse.elementIterator();
		while (getRoomsResponseIterator.hasNext()) {
			Element element = getRoomsResponseIterator.next();
			// 获取查询总数
			if ("total".equals(element.getName())) {
				result.put(element.getName(), element.getText());
			}
			// 获取room节点下的元素
			if ("room".equals(element.getName())) {
				// 用LinkedHashMap 按照顺序添加元素
				listMap = new LinkedHashMap<>();
				Iterator<Element> roomIterator = element.elementIterator();
				
				while (roomIterator.hasNext()) {
					Element roomElement = roomIterator.next();
					// 添加room下的元素
					listMap.put(roomElement.getName(), roomElement.getText());
					Iterator<Element> roomModeIterator = roomElement.elementIterator();
					
					while (roomModeIterator.hasNext()) {
						Element roomModeElement = roomModeIterator.next();
						// 添加RoomMode下的元素
						listMap.put(roomModeElement.getName(), roomModeElement.getText());
					}
				}
				listReult.add(listMap);
			}
		}
		result.put("listReult", listReult);
		
		return result;
	
	}
	
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: getParticipantsResult 暂时废弃
	
	  * @Description: 解析查询会议室人员详情返回的数据，把xml解析成Map集合。
	  * total 为查询的总数
	  * listReult 为查询的会议室人员集合，里面的map存储人员相关元素
	
	  * @param @param xml
	  * @param @return    
	
	  * @return Map<String,Object> 
	
	  * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getParticipantsResult(String xml) throws DocumentException {
		// 要返回的map集合
		Map<String, Object> result = new HashMap<>();
		// 存储room的map集合
		Map<String, Object> listMap = null;
		// 存储listMap的list集合
		List<Map<String, Object>> listReult = new ArrayList<>();
		
		Document dom = DocumentHelper.parseText(xml);
		if (dom == null) {
			return null;
		}
		
		// 获取root 节点
		Element root = dom.getRootElement();
		Element body = root.element("Body");
		Element getParticipantsResponse = body.element(VidyoConstant.GET_PARTICIPANTS_RESPONSE);
		if (getParticipantsResponse == null) {
			return null;
		}
		
		Iterator<Element> getParticipantsResponseIterator = getParticipantsResponse.elementIterator();
		while (getParticipantsResponseIterator.hasNext()) {
			Element element = getParticipantsResponseIterator.next();
			// 获取查询总数
			if ("total".equals(element.getName())) {
				result.put(element.getName(), element.getText());
			}
			
			if ("Entity".equals(element.getName())) {
				listMap = new LinkedHashMap<>();
				Iterator<Element> entityIterator = element.elementIterator();
				while (entityIterator.hasNext()) {
					Element entityElement = entityIterator.next();
					// 添加Entity下的元素
					listMap.put(entityElement.getName(), entityElement.getText());
					Iterator<Element> roomModeIterator = entityElement.elementIterator();
					
					while (roomModeIterator.hasNext()) {
						Element roomModeElement = roomModeIterator.next();
						// 添加RoomMode下的元素
						listMap.put(roomModeElement.getName(), roomModeElement.getText());
					}
					
				}
				listReult.add(listMap);
			}
		}
		result.put("listReult", listReult);
		return result;
		
	}
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: xmlParserMap
	
	  * @Description: 查询会议室，参会人员，返回的xml转换map
	
	  * @param @param xml
	  * @param @return    
	
	  * @return Map<String,Object> 
	
	  * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> xmlParserMap(String xml, String elementName) throws DocumentException {
		Document dom = DocumentHelper.parseText(xml);
		if (dom == null) {
			return null;
		}
		
		// 获取root 节点
		Element root = dom.getRootElement();
		Element body = root.element("Body");
		// 或许要解析的元素的节点
		Element response = body.element(elementName);
		if (response == null) {
			return null;
		}
		// 要返回的map集合
		Map<String, Object> result = new HashMap<>();
		// 存储room的map集合
		Map<String, String> listMap = null;
		// 存储listMap的list集合
		List<Map<String, String>> listReult = new ArrayList<>();
		
		Iterator<Element> responseIterator = response.elementIterator();
		while (responseIterator.hasNext()) {
			Element responseElement = responseIterator.next();
			// 获取查询总数
			if ("total".equals(responseElement.getName())) {
				result.put(responseElement.getName(), responseElement.getText());
			} else {
				listMap = new LinkedHashMap<>();
				Iterator<Element> entityIterator = responseElement.elementIterator();
				while (entityIterator.hasNext()) {
					Element entityElement = entityIterator.next();
					// 添加Entity下的元素
					listMap.put(entityElement.getName(), entityElement.getText());
					Iterator<Element> roomModeIterator = entityElement.elementIterator();
					
					while (roomModeIterator.hasNext()) {
						Element roomModeElement = roomModeIterator.next();
						// 添加RoomMode下的元素
						listMap.put(roomModeElement.getName(), roomModeElement.getText());
					}
					
				}
				listReult.add(listMap);
			}
		}
		result.put("listReult", listReult);
		return result;
		
	}
	public static void main(String[] args) throws DocumentException {
		Map<String, String> elementBody = new HashMap<>();
		elementBody.put("roomID", "72013");
		String xml = getParticipants(elementBody);
		Map<String, Object> map = xmlParserMap(xml, VidyoConstant.GET_PARTICIPANTS_RESPONSE);
		map.forEach((k, v) -> System.out.println(k + " : " + v));
	}
}
